package com.crm.redis.service.cluePoolManager.impl;

import com.alibaba.fastjson.JSONObject;
import com.crm.redis.RedisPrefix;
import com.crm.redis.mapper.ValueRMapper;
import com.crm.redis.service.cluePoolManager.CluePoolStatisticsRedisService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.stereotype.Service;

/**
 * @author luojie
 * @date 2021/2/2 9:26
 */
@Service
public class CluePoolStatisticsRedisServiceImpl implements CluePoolStatisticsRedisService {

    @Autowired
    private StringRedisTemplate redisTemplate;

    private String getUsageCountKey(String cluePoolId) {
        String key = RedisPrefix.CLUE_POOL_USAGE_COUNT + cluePoolId;
        return key;
    }

    private String getReceiveCountKey(String cluePoolId) {
        String key = RedisPrefix.CLUE_POOL_RECEIVE_COUNT + cluePoolId;
        return key;
    }


    @Override
    public Integer getUsageCountById(String cluePoolId) {
        String key = getUsageCountKey(cluePoolId);
        return ValueRMapper.getRedisInteger(redisTemplate, key);
    }

    @Override
    public Boolean setUsageCountById(String cluePoolId) {
        String key = getUsageCountKey(cluePoolId);
        //先查询出redis里面有没有使用数量，没有则赋初始值
        Integer value = ValueRMapper.getRedisInteger(redisTemplate, key);
        if(value==null){
            value = 0;
        }
        boolean result = ValueRMapper.setRedisObject(redisTemplate, key, value+1);
        return result;
    }

    @Override
    public String getReceiveCountForOneMonth(String cluePoolId, Integer month) {
        String key = getReceiveCountKey(cluePoolId);
        Object result = redisTemplate.opsForHash().get(key,month);
        if(result!=null) {
            return JSONObject.toJSONString(result);
        }else {
            return null;
        }
    }

}
